/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.actions.user;

import com.myapp.entity.Uzer;
import com.myweb.MyWeb;
import com.myweb.WebAction;
import com.myweb.WebException;
import com.myweb.WebRequest;
import com.myweb.WebResponse;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TypedQuery;

/**
 *
 * @author DTIT
 */
public class ValidateUser implements WebAction {

  private Uzer user = new Uzer();

  @Override
  public void prepare(WebRequest request) throws WebException {
    if (request.has("username") && request.has("password")) {
      user.setUsername(request.getString("username"));
      user.setPassword(request.getString("password"));
    } else {
      user = null;
    }
  }

  @Override
    public EntityManager process(WebRequest req, WebResponse res, EntityManager em) throws Exception {
    if (user != null) {
      TypedQuery<Uzer> q = em.createQuery("SELECT u FROM Uzer u WHERE u.deleted = false AND u.username = :un AND u.password = :pw", Uzer.class);
      q.setParameter("un", user.getUsername());
      q.setParameter("pw", user.getPassword());
      user = q.getSingleResult();
      req.getSession().setAttribute(MyWeb.KEY_USER, user);
      res.setResult(user);
    }else{
      res.setResult(null);
    }
    return em;
  }
}
